#!/usr/bin/php 
<?php

if(isset($argv[1]) && $argv[1]=="-v")
	$validate=true;
else
	$validate=false;

//Generate perfSONAR NC XML file
require_once("perfsonarnc.cfg.php");
$dom=new DomDocument();
$data=$dom->createElementNS("urn:ietf:params:xml:ns:netconf:base:1.0","data");
$dom->appendChild($data);
$ps=$dom->createElementNS("http://stager.uninett.no/perfsonarnc/1.0","perfSONARNC");
$data->appendChild($ps);
$magroup=$dom->createElementNS("http://stager.uninett.no/perfsonarnc/1.0","measurementArchivesAndQueries");
$ps->appendChild($magroup);
$mas=$dom->createElementNS("http://stager.uninett.no/perfsonarnc/1.0","mas");
$magroup->appendChild($mas);
$xp=new domxpath($dom);
$xp->registerNamespace("pn","http://stager.uninett.no/perfsonarnc/1.0");
//Load and initialize available MA
$index=1;
$ma=array();
foreach($cfg['ma'] as $name=>$class) {
	if(is_file($class)) {		
		require_once($class);
		$ma[$index]=new $name;
		try {
			$mas->appendChild($ma[$index]->initDOM($index,$dom,$xp));
		} catch (Exception $e) {
			print "Error: ".$e->getMessage();
		}
		$index++;
	} else {
		print "Error: Could not load MA - $class\n";
	}
}
$magroup->appendChild($dom->createElementNS("http://stager.uninett.no/perfsonarnc/1.0","queries"));

$out=fopen($cfg['xml'].".tmp","w");
fwrite($out,$dom->saveXML());
fclose($out);

if($validate) {
	//Validate	
	print "yang2dsdl -s -b pnc -d ".$cfg['dsdl']." -v ".$cfg['xml'].".tmp \n";
	exec("yang2dsdl -s -b pnc -d ".$cfg['dsdl']." -v ".$cfg['xml'].".tmp 2>&1",$out,$ret);
	if($ret==0)
		print "XML validated\n";
	else
		die("Error validating XML:\n".print_r($out,true)."\n");
} else print "XML not validated\n";

if(file_exists($cfg['xml']))
	unlink($cfg['xml']);
rename($cfg['xml'].".tmp",$cfg['xml']);

?>